package com.zhongxi.guoyuan.OffLineShop;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;

import com.zhongxi.guoyuan.OffLineShop.ConnectNet.NetWork;
import com.zhongxi.guoyuan.OffLineShop.Model.ItemShopInfo;
import com.zhongxi.guoyuan.OffLineShop.Model.SuccessPay;
import com.zhongxi.guoyuan.OffLineShop.UrlOffLine.RelativeUrl;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.utils.DataUtil;
import com.zhongxi.guoyuan.utils.ToastUtil;
import com.zhongxi.guoyuan.utils.UiUtils;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Administrator on 2018/4/12.
 */

public class MentDetailFragment extends OffLineBaseFragment {

    @Bind(R.id.tv_time)
    TextView mTvTime;
    @Bind(R.id.tv_orderId)
    TextView mTvOrderId;
    @Bind(R.id.tv_storeName)
    TextView mTvStoreName;
    @Bind(R.id.tv_discount)
    TextView mTvDiscount;
    @Bind(R.id.tv_phone)
    TextView mTvPhone;
    @Bind(R.id.tv_address)
    TextView mTvAddress;
    @Bind(R.id.tv_shouldPrice)
    TextView mTvShouldPrice;
    @Bind(R.id.tv_truePrice)
    TextView mTvTruePrice;
    @Bind(R.id.tv_hongdou)
    TextView mTvHongdou;
    @Bind(R.id.tv_meidou)
    TextView mTvMeidou;
    @Bind(R.id.tv_opatinWay)
    TextView mTvOpatinWay;
    @Bind(R.id.tv_score)
    TextView mTvScore;
    @Bind(R.id.ratingBar)
    RatingBar mRatingBar;
    @Bind(R.id.tv_nocomment)
    TextView mTvNocomment;
    @Bind(R.id.tv_comment)
    TextView mTvComment;
    @Bind(R.id.btn_click)
    Button mBtnClick;
    private SuccessPay mSuccessPay;
    private ProgressDialog mDialog;
    private SuccessPay.SuccessOrder mOrder;
    private ItemShopInfo mStore;

    @Override
    protected void initParams() {
        super.initParams();
        if (getArguments() != null) {
            mSuccessPay = (SuccessPay) getArguments().getSerializable("mentdetail");
        }
    }

    @Override
    protected View init() {
        View mView = UiUtils.inflate(R.layout.fragment_mentdetail);
        ButterKnife.bind(this, mView);
        return mView;
    }

    @Override
    protected void initView(View view) {
        super.initView(view);
        if (mSuccessPay.order != null && !"".equals(mSuccessPay.order)) {
            mOrder = mSuccessPay.order;
            mTvTime.setText("结账时间:    " + mOrder.ctime);
            mTvOrderId.setText("订单编号:    " + mOrder.id);
            if ("100".equals(mOrder.storediscount)) {
                mTvDiscount.setText("无折扣");
            } else {
                mTvDiscount.setText(mOrder.storediscount + "折扣");
            }
            mTvShouldPrice.setText("应该支付:    " + mOrder.shouldprice + " 元");
            mTvTruePrice.setText("实际支付:    " + mOrder.payprice + " 元");
            mTvHongdou.setText("立刻奖励:    " + mOrder.backcashnum + " 元");
            mTvMeidou.setText("立刻奖励:    " + mOrder.backinnernum + " 美豆");
            if (1 == mOrder.scene) {
                mTvOpatinWay.setText("进入方式:    线上店铺");
            } else if (2 == mOrder.scene) {
                mTvOpatinWay.setText("进入方式:    线下扫码");
            } else if (3 == mOrder.scene) {
                mTvOpatinWay.setText("进入方式:    商家中心扫码");
            }
        }
        if (mSuccessPay.store != null && !"".equals(mSuccessPay.store)) {
            mStore = mSuccessPay.store;
            mTvStoreName.setText("收款商家:    " + mStore.getName());
            mTvPhone.setText("商家电话    " + mStore.getPhone());
            mTvAddress.setText("商家地址:    " + mStore.getAddress());
        }
        if (mSuccessPay.comment != null && !"".equals(mSuccessPay.comment)) {
            SuccessPay.Comment mComment = mSuccessPay.comment;
            if (!TextUtils.isEmpty(mComment.content)) {
                mBtnClick.setVisibility(View.GONE);
                mTvNocomment.setVisibility(View.GONE);
                mRatingBar.setVisibility(View.VISIBLE);
                mRatingBar.setRating(mComment.starlevel);
                mTvScore.setVisibility(View.GONE);
                mTvComment.setText(mComment.content);
            } else {
                mBtnClick.setVisibility(View.VISIBLE);
                mTvScore.setVisibility(View.VISIBLE);
                mRatingBar.setVisibility(View.GONE);
                mTvNocomment.setVisibility(View.VISIBLE);
                mTvComment.setText("您还未评论哟!");
            }
        } else {
            mBtnClick.setVisibility(View.VISIBLE);
            mTvScore.setVisibility(View.VISIBLE);
            mRatingBar.setVisibility(View.GONE);
            mTvNocomment.setVisibility(View.VISIBLE);
            mTvComment.setText("您还未评论哟!");
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @OnClick(R.id.btn_click)
    public void onViewClicked() {
        final AlertDialog mDialog = new AlertDialog.Builder(getActivity()).create();
        View view = UiUtils.inflate(R.layout.dialog_pay_success_offline);
        ImageView mImageVie = (ImageView) view.findViewById(R.id.iv_cancel);
        final RatingBar mRatingBar = (RatingBar) view.findViewById(R.id.ratingBar);
        final EditText et_evaluate = (EditText) view.findViewById(R.id.et_evaluate);
        final TextView long_evaluate = (TextView) view.findViewById(R.id.long_evaluate);
        Button btn_reset = (Button) view.findViewById(R.id.btn_reset);
        Button btn_submit = (Button) view.findViewById(R.id.btn_submit);
        mImageVie.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mDialog.dismiss();
            }
        });
        btn_reset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mRatingBar.setRating(0);
                et_evaluate.setText("");
            }
        });
        btn_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String mTrim = et_evaluate.getText().toString().trim();
                if (!TextUtils.isEmpty(mTrim) && mRatingBar.getRating() != 0) {
                    mDialog.dismiss();
                    String rb = String.valueOf(mRatingBar.getRating());
                    addComment(mTrim, Integer.parseInt(rb.substring(0, rb.indexOf("."))));
                } else {
                    ToastUtil.show(getString(R.string.comment_nofinish));
                }
            }
        });
        et_evaluate.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                long_evaluate.setText("0/200");
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                long_evaluate.setText(s.length() + "/200");
            }
        });
        mDialog.setCanceledOnTouchOutside(false);
        mDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialogInterface, int i, KeyEvent keyEvent) {
                if (i == KeyEvent.KEYCODE_BACK && keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
                    mDialog.dismiss();
                    return true;
                }
                return false;
            }
        });
        mDialog.setView(view);
        mDialog.show();
    }

    private void addComment(final String trim, int rating) {
        mBtnClick.setVisibility(View.GONE);
        mTvNocomment.setVisibility(View.GONE);
        mRatingBar.setVisibility(View.VISIBLE);
        mRatingBar.setRating(rating);
        mTvScore.setVisibility(View.GONE);
        mTvComment.setText(trim);
        unsubscribe();
        mDisposable = NetWork.getOffLineApi().addCommentApi(RelativeUrl.ADDCOMMENT + MyApplication.getInstance().getUrl(),
                MyApplication.getInstance().getCheck(false), mStore.getId(), mOrder.id, rating, trim)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        if (mDialog == null) {
                            mDialog = ProgressDialog.show(getActivity(), "提示", "正在加载中...");
                        }
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<BaseResponse>() {
                    @Override
                    public void accept(BaseResponse baseResponse) throws Exception {
                        if (mDialog != null && mDialog.isShowing()) {
                            mDialog.dismiss();
                        }
                        MyApplication.getInstance().setSpValue(baseResponse.getSafeobj());
                        if (baseResponse.getCode() != 1) {
                            ToastUtil.show(getString(R.string.losePay, baseResponse.getCode()));
                        } else {
                            ToastUtil.show("评论成功!");
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        if (mDialog != null && mDialog.isShowing()) {
                            mDialog.dismiss();
                        }
                        ToastUtil.show(getString(R.string.load_error));
                    }
                });
    }
}
